package com.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtil {
    private static Connection conn;
    private static ThreadLocal<Connection> tl=new ThreadLocal<Connection>();
    private static Properties  pro=new Properties();
    static{
        InputStream is=JDBCUtil.class.getClassLoader().getResourceAsStream("com/config/jdbc.properties");	
        try {
			pro.load(is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    throw new ExceptionInInitializerError("静态代码块出错");
		}
    }
    public static Connection getConnection() throws Exception{
    	conn=tl.get();
    	if(conn==null){
    		//1: 注册Driver驱动
        	Class.forName(pro.getProperty("driver"));
        	//2: 获取Connection连接
        	//url
        	String url=pro.getProperty("url");
        	//user
        	String user=pro.getProperty("user");
        	//password
        	String password=pro.getProperty("password");
        	conn=DriverManager.getConnection(url, user, password);
        	tl.set(conn);
    	}
    	return conn;
    }
	
    public static  void closeResourse(ResultSet rs,PreparedStatement ps,Connection conn){
    	if(rs!=null){
    		try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	if(ps!=null){
    		try {
				ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	if(conn!=null){
    		try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	
    }
	
	
	
}
